﻿using System;
using System.Windows.Input;

namespace Softelligent.Zintra.Demos.Events.PublishShell.Commands
{
    public class DelegateCommand : ICommand
    {
        private readonly Func<bool> canExecuteMethod;
        private readonly Action executeMethod;

        public DelegateCommand(Action executeMethod)
            : this(executeMethod, null)
        {
        }

        public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
        {
            if (executeMethod == null)
            {
                throw new ArgumentNullException("executeMethod");
            }
            this.executeMethod = executeMethod;
            this.canExecuteMethod = canExecuteMethod;
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (canExecuteMethod == null) return;
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (canExecuteMethod == null) return;
                CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(object parameter)
        {
            if (canExecuteMethod == null)
            {
                return true;
            }
            return canExecuteMethod.Invoke();
        }

        public void Execute(object parameter)
        {
            executeMethod.Invoke();
        }

        public void RaiseCanExecuteChanged()
        {
            CommandManager.InvalidateRequerySuggested();
        }
    }
}
